package com.rj.framework.component;

import com.rj.framework.component.interceptor.ComponentInterceptor;
import com.rj.framework.context.Context;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 增强的组件注册表，解决类型兼容性问题
 */
public class ComponentRegistry {
    private final Map<Class<? extends BusinessComponent>, BusinessComponent> businessComponentMap = new ConcurrentHashMap<>();
    private final Map<Class<? extends TechnicalComponent>, TechnicalComponent> technicalComponentMap = new ConcurrentHashMap<>();
    private final List<ComponentInterceptor> interceptors = new ArrayList<>();

    public void registerBusinessComponent(BusinessComponent component) {
        businessComponentMap.put(component.getClass(), component);

    }

    public void registerTechnicalComponent(TechnicalComponent component) {
        technicalComponentMap.put(component.getClass(), component);
    }

    public void addComponentInterceptor(ComponentInterceptor component) {
        interceptors.add(component);
    }

    @SuppressWarnings("unchecked")
    public <I, O, C extends Context<?>> BusinessComponent<I, O, C> getBusinessComponent(Class<? extends BusinessComponent<I, O, C>> componentClass) {
        BusinessComponent<I, O, C> component = businessComponentMap.get(componentClass);
        if (component == null) {
            throw new IllegalArgumentException("Component not found: " + component.getClass());
        }
        String simpleName = component.getClass().getSimpleName();
        for (ComponentInterceptor interceptor : interceptors) {
            component = interceptor.intercept(component, simpleName);
        }
        return component;
    }

    @SuppressWarnings("unchecked")
    public <I, O, C extends Context<?>> TechnicalComponent<I, O, C> getTechnicalComponent(Class<? extends TechnicalComponent<I, O, C>> componentClass) {
        TechnicalComponent<I, O, C> component = technicalComponentMap.get(componentClass);
        if (component == null) {
            throw new IllegalArgumentException("Component not found: " + component.getClass());
        }
        return component;
    }

}
